var cookieHandle={
    getCookie:function (param){
        let name = param + '=';
        let cookieList = document.cookie.split(';');
        for (var i =0;i<cookieList.length;i++){
            var c = cookieList[i].trim();
            if(c.indexOf(name) === 0){
                return c.substring(name.length,c.length);
            }
        }
    },
    setCookie:function (param){
        for (let index in param){
            document.cookie = index + '=' + param[index] +';path=/';
        }
    }
}
var service={
    socket:io('?user_id='+cookieHandle.getCookie('id')),
    user:{
        closepopup:function (){
          $('#confirm_login').popup('close');
        },
        login:function (){
            $('#form_login').on('submit',function (event){
               event.preventDefault();
               let formLoginData={
                   'account':$('#user_account_login').val(),
                   'password':$('#user_password_login').val()
               };
               $.post('/user/dologin',formLoginData,function (data){
                   if(data.state===200){
                       $('#confirm_login p').text('登录成功');
                       $('#confirm_login').popup('open').on('popupafterclose',function(){
                         cookieHandle.setCookie(data.data[0]);
                         cookieHandle.setCookie(data.extra);
                         $.mobile.changePage('chatList.html');
                       });
                   }
                   else{
                       $('#confirm_login p').text('用户名或密码错误')
                       $('#confirm_login').popup('open');
                   }
               })
            });
        }
    },
    chat:{
      chatList:function(){
        $.get('/message/getlist',{
          'user_id':cookieHandle.getCookie('id'),
          'token':cookieHandle.getCookie('token')
        },function (data){
          if(data.state===200){
            let listStr="";
            for(let index in data.data){
              listStr=listStr+'<li><a href="javascript:void(0)" data-id="'+index+'"><img src="/'+data.data[index].head_img+'"/><h2>'+data.data[index].nickname+'</h2><p>'+data.data[index].content+'</p></a></li>'
            }
            $('#chat_friend_list').html(listStr).listview('refresh');
            $('#chat_friend_list li a').on('tap',function(){
              sessionStorage.chatFriendInfo=JSON.stringify({
                'id':data.data[$(this).data('id')].id,
                'nickname':data.data[$(this).data('id')].nickname,
                'head_img':data.data[$(this).data('id')].head_img,
              })
              $.mobile.changePage('chatWin.html')
            })
          }
          else if(data.state===500){
              $.mobile.changePage('login.html')
          }
          else{
              $('#confirm_message p').text(data.msg)
              $('#confirm_message').popup('open');
          }
        })
      },
      chatWin:function (){
        let chatFriendInfo=JSON.parse(sessionStorage.chatFriendInfo);
        let friendId=chatFriendInfo.id;
        let head_img=chatFriendInfo.head_img;
        $("#win_friend_nickname").text(chatFriendInfo.nickname);
        $.get('/message/user/list',{
          'user_id':cookieHandle.getCookie('id'),
          'friend_id':friendId,
          'token':cookieHandle.getCookie('token')
        },function (data){
            if(data.state===200) {
                let messageStr = '';
                for (let index in data.data) {
                    if (data.data[index].send_user_id === cookieHandle.getCookie('id')) {
                        let create_time = new Date(data.data[index].create_time);
                        messageStr = messageStr + '<li class="self_message"><p class="time"><span>' + create_time.getFullYear() + "-" + (create_time.getMonth() + 1) + "-" + create_time.getDate() + " " + create_time.getHours() + ":" + create_time.getMinutes() + '</span></p><div class="main self"><img class="photo" src="/' + cookieHandle.getCookie('head_img') + '"/><div class="text">' + data.data[index].content + '</div></div></li>';
                    } else {
                        let create_time = new Date(data.data[index].create_time);
                        messageStr = messageStr + '<li class="self_message"><p class="time"><span>' + create_time.getFullYear() + "-" + (create_time.getMonth() + 1) + "-" + create_time.getDate() + " " + create_time.getHours() + ":" + create_time.getMinutes() + '</span></p><div class="main"><img class="photo" src="/' + head_img + '"/><div class="text">' + data.data[index].content + '</div></div></li>';
                    }
                }
                $('#message_list').hide(0).append(messageStr).show(function () {
                    $.mobile.silentScroll(parseInt($('#message_list').css('height')));
                })
            }
            else if(data.state===500){
                $.mobile.changePage('login.html')
            }
            else{
                $('#confirm_message p').text(data.msg)
                $('#confirm_message').popup('open');
            }
        })
        let time=new Date();
        $('#btn_sendMessage').on('tap',function (){
          if($('#message_text').val()===""){return false}
          else{
            let messageStr='<li class="self_message"><p class="time"><span>'+time.getFullYear()+"-"+(time.getMonth()+1)+"-"+time.getDate()+" "+time.getHours()+":"+time.getMinutes()+'</span></p><div class="main self"><img class="photo" src="/'+cookieHandle.getCookie('head_img')+'"><div class="text">'+$('#message_text').val()+'</div></div></li>';
            $('#message_list').append(messageStr);
              $.mobile.silentScroll(parseInt($('#message_list').css('height')));
              $.post('/message/message',{'content':$('#message_text').val(),'user_id':cookieHandle.getCookie('id'),'friend_id':friendId,'token':cookieHandle.getCookie('token')});
              service.socket.emit('sendMessage',{
                'content':$('#message_text').val(),
                'friend_id':friendId,
                'nickname':chatFriendInfo.nickname,
                'user_id':cookieHandle.getCookie('id'),
                'token':cookieHandle.getCookie('token')
              })
              $('#message_text').val('');
          }
        });
      },
      chatCanvas:function (){
        let id=cookieHandle.getCookie('id');
        let data={};
        let length=0;
        let maxNum=0;
        var drawLine=function (ctx){
          ctx.strokeStyle="black";
          ctx.beginPath();
          ctx.moveTo(250,50);
          ctx.lineTo(50,50);
          ctx.lineTo(50,450);
          ctx.stroke();
        }
        let drawIndex=function (ctx,data){
          ctx.font='10px serif';
          var num=400/length;
          let i=1;
          for(let val in data){
            ctx.fillText(data[val].date,0,50+num*i++-num/2);
          }
          let j=maxNum/4;
          for(let k=1;k<=4;k++){
            ctx.fillText(j*k,50*k+40,40);
          }
        }
        let drawPillar=function (ctx,data){
          var num=400/length;
          var i=1;
          ctx.shadowOffsetX=2;
          ctx.shadowOffsetY=2;
          ctx.shadowBlur-2;
          ctx.shadowColor='rgba(0,0,0,0.5)';
          for(var val in data){
            var lineargradient=ctx.createLinearGradient(50,50,450,450);
            lineargradient.addColorStop(0,"black");
            lineargradient.addColorStop(1,'blue');
            ctx.fillStyle=lineargradient;
            ctx.fillRect(50,50+num*i-num+100/length,data[val].count/maxNum*200,num-100/length*2);
          }
        }
        let drawMsg=function (ctx,msg){
          var w = ctx.canvas.width;
          var h = ctx.canvas.height;
          ctx.beginPath();
          ctx.font = "40px Microsoft YaHei";
          //水平对齐方式
          ctx.textAlign = "center";
          //垂直对齐方式
          ctx.textBaseline = "middle";
          ctx.fillText(msg, w / 2, h / 2);
        }
        var date=new Date();
        var dateStart=new Date(date.getTime()-10*24*60*60*1000);
        var dateEnd=new Date(date.getTime()+24*60*60*1000);
        var time_start=dateStart.getFullYear()+'-'+(dateStart.getMonth()+1)+'-'+dateStart.getDate();
        var time_end=dateEnd.getFullYear()+'-'+(dateEnd.getMonth()+1)+'-'+dateEnd.getDate();
        let canvas=document.getElementById('canvas');
        let ctx=canvas.getContext('2d');
        $.get('/message/search/count',{'id':id,'time_start':time_start,'time_end':time_end,'token':cookieHandle.getCookie('token')},function (result){
          data=result.data.data;
          if(data.state===200){
              if(data.length>0){
                  for(let index in data){
                      maxNum+=data[index].count;
                      length++;
                  }
                  drawLine(ctx);
                  drawIndex(ctx,data);
                  drawPillar(ctx,data);
              }
              else{
                  drawMsg(ctx,'暂无数据')
              }
          }
          else if(data.state===500){
              $.mobile.changePage('login.html')
          }
          else{
              $('#confirm_message p').text(data.msg)
              $('#confirm_message').popup('open');
          }
        });
      }
    }
}
$(document).on("pagecreate",'#page_login', function( ) {
  service.user.login();
});
$(document).on( "pagecreate",'#page_chat_list', function( e, data ) {
  service.chat.chatList();
});
$(document).on( "pagecreate",'#page_chat_win', function( e, data ) {
  service.chat.chatWin();
});
$(document).on( "pagecreate",'#page_chat_canvas', function( e, data ) {
  service.chat.chatCanvas();
});
service.socket.on('receiveMessage',function (data){
  if($('#message_list').length>0){
    let create_time=new Date()
    let chatFriendInfo=JSON.parse(sessionStorage.chatFriendInfo);
    let head_img=chatFriendInfo.head_img;
    let messageStr='<li class="self_message"><p class="time"><span>'+create_time.getFullYear()+"-"+(create_time.getMonth()+1)+"-"+create_time.getDate()+" "+create_time.getHours()+":"+create_time.getMinutes()+'</span></p><div class="main"><img class="photo" src="/'+head_img+'"/><div class="text">'+data.content+'</div></div></li>';
    $('#message_list').append(messageStr);
    $.mobile.silentScroll(parseInt($('#message_list').css('height')));
  }
  else{
    alert('好友'+data.friend_id+'发来信息:'+data.content);
  }
});
